package com.zhanglinwei.openApiClient.wrapper;


import com.zhanglinwei.openApiClient.function.SFunction;
import com.zhanglinwei.openApiClient.model.entity.OpenApiEntity;
import com.zhanglinwei.openApiClient.model.response.lambda.LambdaOpenApiResponse;
import com.zhanglinwei.openApiClient.utils.ClassUtils;
import com.zhanglinwei.openApiClient.utils.LambdaUtils;
import com.zhanglinwei.openApiClient.utils.PropertyUtils;
import lombok.Getter;

import java.lang.invoke.SerializedLambda;

@Getter
public abstract class AbstractLambdaWrapper<T extends OpenApiEntity<? extends LambdaOpenApiResponse<?>>, W extends AbstractLambdaWrapper<T, W>>
        extends AbstractWrapper<T, SFunction<T, ?>, W>{

    @Override
    protected String columnToString(SFunction<T, ?> column) {
        if (column == null) {
            throw new IllegalArgumentException("column function can not be null");
        }

        SerializedLambda serializedLambda = LambdaUtils.parseLambda(column);
        initEntityClass(serializedLambda, column);
        return PropertyUtils.methodToProperty(serializedLambda.getImplMethodName());
    }

    private void initEntityClass(SerializedLambda lambda, SFunction<T, ?> func) {
        if (getEntityClass() == null) {
            String instantiatedMethodType = lambda.getInstantiatedMethodType();
            String instantiatedType = instantiatedMethodType.substring(2, instantiatedMethodType.indexOf(";")).replace("/", ".");
            setEntityClass((Class<T>) ClassUtils.toClassConfident(instantiatedType, func.getClass().getClassLoader()));
        }
    }




}
